import 'package:async/async.dart';
import 'package:boss/main.dart';
import 'package:boss/models/package_group.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';

class PackageGroupProvider extends ChangeNotifier {
  List<PackageGroup> packageGroups = [];

  Future<Result<List<PackageGroup>>> initData() async {
    try {
      var res = await api.queryPackageGroups();

      if (!res.successful()) {
        return Result.value([]);
      }

      packageGroups = res.data;
      notifyListeners();

      return Result.value(res.data);
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  bool _checkPackageGroup(PackageGroup packageGroup) {
    if (!RegUtil.testNotEqEmpty(packageGroup.groupName)) {
      toast('请输入套餐分组名称');
      return false;
    }

    if (packageGroup.commodityFormList.length == 0) {
      toast('请选择套餐分组菜品');
      return false;
    }

    if (!packageGroup.isDuplicated && packageGroup.count > packageGroup.commodityFormList.length) {
      toast('菜品必点数量不能大于套餐菜品数量');
      return false;
    }

    return true;
  }

  Future<bool> plusPackageGroup(PackageGroup packageGroup) async {
    try {
      if (!_checkPackageGroup(packageGroup)) return false;

      showLoadingToast();

      var res = await api.addPackageGroup(packageGroup);
      if (!res.successful()) {
        toast(res.msg);
        return false;
      }

      toast('添加成功');

      packageGroup.id = res.data.id;
      packageGroups.add(res.data);
      notifyListeners();

      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }

  Future<bool> resetPackageGroup(PackageGroup packageGroup) async {
    try {
      if (!_checkPackageGroup(packageGroup)) return false;

      showLoadingToast();

      var res = await api.updatePackageGroup(packageGroup);
      if (!res.successful()) {
        toast(res.msg);
        return false;
      }

      toast('修改成功');

      var index = packageGroups.indexWhere((item) => item.id == packageGroup.id);
      packageGroups[index] = packageGroup;
      notifyListeners();

      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }

  Future<bool> removePackageGroup(int id) async {
    try {
      showLoadingToast();

      var res = await api.deletePackageGroup(id);
      if (!res.successful()) {
        toast(res.msg);
        return false;
      }
      toast('删除成功');

      packageGroups.removeWhere((item) => item.id == id);
      notifyListeners();

      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }
}
